import time
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from taobao_check.tools import click_by_js
from .base import BaseBrush


class Wanmuliyu(BaseBrush):
    login_url = "http://xmly.ake069.com/seller/#/login"
    index_url = "http://xmly.ake069.com/seller/#/users/notice/index"
    check_url = "http://xmly.ake069.com/seller/#/reviewBuyer"

    def __init__(self, config, tab):
        super().__init__("万亩鲤鱼", "wanmuliyu", config, tab)
        self.memory_limit = 800

    def login(self):
        if self.browser.current_url != self.login_url:
            self.browser.get(self.login_url)

        self.enter_text((By.CSS_SELECTOR, "input[type='text']"), self.username)
        self.enter_text((By.CSS_SELECTOR, "input[type='password']"), self.password)
        self.click_button((By.CSS_SELECTOR, "button[type='button']"))

        while self.browser.current_url != self.index_url:
            time.sleep(0.1)

        self.browser.get(self.check_url)

    def check_user(self):
        self.sleep(1)
        try:
            tr = self.find_element((By.CSS_SELECTOR, "div.is-scrolling-none>table>tbody>tr"))
        except TimeoutException:
            self.print_log("没有买号.", debug=True)
            self.sleep(self.refresh_time)
            return False
        tds = tr.find_elements_by_css_selector("td>div.cell")
        self.print_log("发现待验买号.")
        username = tds[-2].get_attribute('textContent').strip()
        username = username.split()[0]
        self.print_log(f"当前待验买号为：【{username}】")
        start = time.time()
        result = self.check.check_user(username, self.print_log)
        self.print_log(f"验号结果为: {'通过' if result else '不通过'}. 用时: {time.time()-start:.2f}s")

        start_button, rematch_button = tds[-1].find_elements_by_tag_name("button")
        if result:
            click_by_js(self.browser, start_button)
            ok_button = self.find_button((By.CSS_SELECTOR, "div.el-message-box__btns>button.el-button--primary"))
            click_by_js(self.browser, ok_button)
            self.print_log("开始任务.\n")
        else:
            click_by_js(self.browser, rematch_button)
            ok_button = self.find_button((By.CSS_SELECTOR, "div.el-message-box__btns>button.el-button--primary"))
            click_by_js(self.browser, ok_button)
            self.print_log("开始重新匹配买号.\n")
        return True
